// pages/detail/detail.js
const app = getApp()
var plugin = requirePlugin("WechatSI")
var manager = plugin.getRecordRecognitionManager() //录音组件
var innerAudioContext = wx.createInnerAudioContext() //播音组件
var dateTimePicker = require('../../utils/dateTimePicker');
var uuidGen = require('../../utils/_uuid');
const baseUrl = getApp().globalData.baseUrl
// var imageUuid
// var videoUuid
// var audioUuid

const eventTypes = {}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: getApp().globalData.userInfo,
    phoneNum: getApp().globalData.phoneNum,
    type: '',
    todoId: '',
    dealwith: '',
    // eventListObj: {},
    eventListObj:{},
    imageUuid: '',
    videoUuid: '',
    audioUuid: '',
   // 控件
   options: {
    showPopup: false,
    currentClickItem: '',
    maxPhotoCount: 4,
    maxVideoCount: 2,
    maxRecordCount: 3,
    recordStatus: [0, 0, 0] //-1暂停,1播放中,0一般
  },
  // 表单数据
  formData: {
    eventName: '',
    eventType: [],
    text: '',
    address: '',
    level: '',
    time: '',
    appealUser: '',
    appealPhoneNum: '',
  },
    // 初始化数据
  typeItems: [
    // {
    //   values: Object.keys(eventTypes),
    //   className: 'column1',
    //   defaultIndex: 0,
    // },
    // {
    //   values: eventTypes['社会治安'],
    //   className: 'column2'
    // },
  ],
  levelItems: ['一般', '急', '特急'],
  photosList: [],
  videosList: [],
  recordList: [],
  dateTimeArray: null,
  dateTime: null,
  startYear: 2000,
  endYear: 2050,
  voiceUrlList: [1,2,3]
},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      type: options.type,
      todoId: options.todoId,
      dealwith: options.dealwith,
    })
    console.log(this.data.type,this.data.todoId,this.data.dealwith)
    this.initUuid()
    this.detailInfo()
    this.initTimePicker()
    this.initRecord()
    this.getDictInfo()
    let that = this
    getApp().watchUserInfo(that.watchBackUserInfo)
    getApp().watchPhoneNum(that.watchBackPhoneNum)
  },
  watchBackUserInfo(userInfo) {
    console.log('监听到的数据userInfo：' + userInfo)
    let that = this
    that.setData({
      userInfo: userInfo
    })
  },
  watchBackPhoneNum(phoneNum) {
    console.log('监听到的数据phoneNum：' + phoneNum)
    let that = this
    that.setData({
      phoneNum: phoneNum
    })
  },
  // 详情信息
  detailInfo() {
    let todoId = this.data.todoId
    let that = this
    let url = `${baseUrl}/api/eventTodo/detail?todoId=${todoId}`
    wx.request({
      url: url,
      header: {
        "token": wx.getStorageSync('token'),
        // "token": "fdb07f065c214892899dcc691841fa4e"
      },
      method: 'GET',
      success: function(res) {
        if(res.data.code === 0) {
          that.setData({
            eventListObj: res.data.eventTodoVO
          })
        }
        console.log(res)
      },
      fail: function(err) {
        console.log(err)
      }
    })
  },

  //返回首页
  // goIndex() {
  //   wx.navigateTo({
  //     url: '../index/index',
  //   })
  // },

  // 事件类别
  eventTypeChange(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    picker.setColumnValues(1, eventTypes[value[0]]);
  },

  // 文本双向绑定
  setFormValue(e) {
    let {
      formData,
      options
    } = this.data
    console.log(e.target)
    console.log(e.detail.value)
    formData[e.target.dataset.name] = e.detail.value
    options.showPopup = false
    this.setData({
      formData,
      options
    })
  },
  // 选择框双向绑定
  bindPickerChange(e) {
    let formData = this.data.formData
    let objectArray = this.data[e.target.dataset.optionsName]
    formData[e.target.dataset.name] = objectArray[e.detail.value].id
    formData[e.target.dataset.name + 'Label'] = objectArray[e.detail.value].name
    this.setData({
      formData
    })
  },

  // 选择媒体文件
  bindChooseFile(e) {
    let {
      file
    } = e.detail
    let {
      imageUuid,
      videoUuid,
      audioUuid
    } = this.data
    const {
      name: type
    } = e.target.dataset
    if (type === 'image') {
      let index = this.data.photosList.length
      let photosList = this.data.photosList.concat(file)
      this.setData({
        photosList
      })
      this.uploadFile(photosList, index, imageUuid, 0)
    } else if (type === 'video') {
      let index = this.data.videosList.length
      let videosList = this.data.videosList.concat(file)
      this.setData({
        videosList
      })
      this.uploadFile(videosList, index, videoUuid, 1)
    }
  },
  // 删除文件
  bindDeleteFile(e) {
    let that = this
    const {
      photosList,
      videosList
    } = this.data
    const {
      name: type
    } = e.target.dataset
    wx.showModal({
      title: "提示",
      content: "是否删除",
      success: function (res) {
        if (res.confirm) {
          if (type === "image") {
            photosList.splice(e.detail.index, 1)
            that.setData({
              photosList
            })
          } else if (type === "video") {
            videosList.splice(e.detail.index, 1)
            that.setData({
              videosList
            })
          }
        } else if (res.cancel) {
          console.log("用户点击取消")
        }
      }
    })
  },
 // 初始化时间picker
 initTimePicker() {
  // 获取完整的年月日 时分秒，以及默认显示的数组
  var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
  this.setData({
    dateTime: obj.dateTime,
    dateTimeArray: obj.dateTimeArray
  });
},
// 双向绑定日期时间控件
changeDateTime(e) {
  this.setData({
    dateTime: e.detail.value
  });
  let dateTimeArray = this.data.dateTimeArray
  let dateTime = this.data.dateTime
  let time = dateTimeArray[0][dateTime[0]] + '-' + dateTimeArray[1][dateTime[1]] + '-' + dateTimeArray[2][dateTime[2]] + ' ' + dateTimeArray[3][dateTime[3]] + ':' + dateTimeArray[4][dateTime[4]] + ':' + dateTimeArray[5][dateTime[5]]
  let formData = this.data.formData
  formData[e.target.dataset.name] = time
  this.setData({
    formData
  })
},
// 日期时间列选择变化
changeDateTimeColumn(e) {
  var arr = this.data.dateTime,
    dateArr = this.data.dateTimeArray;
  arr[e.detail.column] = e.detail.value;
  dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
  this.setData({
    dateTimeArray: dateArr,
    dateTime: arr
  });
},
//  时间分类级联框初始化值
initEventPicker() {
  let objectArray2 = this.data.objectArray2
  objectArray2[0] = this.data.objectArrayTree
  objectArray2[1] = this.data.objectArrayTree[0].children
  this.setData({
    objectArray2: objectArray2
  })
},
  //  级联选择器列变化
  mulPickerColChange(e) {
    if (e.detail.column === 0) {
      let objectArray2 = this.data.objectArray2
      objectArray2[e.detail.column + 1] = this.data.objectArrayTree[e.detail.value].children
      this.setData({
        objectArray2: objectArray2
      })
    }
  },
  //  级联选择器双向绑定数据
  mulPickerChange(e) {
    let formData = this.data.formData
    let obj = this.data[e.target.dataset.optionsName][e.detail.value.length - 1][e.detail.value[e.detail.value.length - 1]]
    formData[e.target.dataset.name] = obj.id
    formData[e.target.dataset.name + 'Label'] = obj.name
    this.setData({
      formData
    })
    console.log(obj, this.data.formData)
  },
  getMap() {
    let that = this
    wx.chooseLocation({
      success: function (res) {
        let name = res.name
        let address = res.address
        let latitude = res.latitude
        let longitude = res.longitude
        let formData = that.data.formData
        formData.address = res.address
        that.setData({
          formData
        })
        console.log(res)
      }
    })
  },
  /*
  文件上传
  */
  uploadFile(fileList, index, uuid, type) {
    let that = this
    let path = fileList[index].path || fileList[index].url
    wx.uploadFile({
      url: `${baseUrl}/api/file/uploadFile`,
      filePath: path,
      name: 'file',
      formData: {
        //上传数据
        uuid: uuid,
        file: path,
        type: type
      },
      success(res) {
        // set.setData({
        //   'TIP': '第' + (index + 1) + '个文件上传成功'
        // });
        if (index + 1 == fileList.length) {
          // wx.showModal({
          //   title: '提示',
          //   content: '上传成功',
          //   success: function (res) {
          //   }
          // })
        } else {
          that.uploadFile(fileList, index + 1, uuid, type);
        }
      },
      fail(res) {
        wx.showModal({
          title: '提示',
          content: '上传失败，请删除',
          showCancel: false,
          success: function (res) {}
        })
      }
    })
  },

   // 录音
   streamRecord() {
    if (this.data.recordList.length < this.data.options.maxRecordCount) {
      manager.start({
        duration: 60000,
        lang: "zh_CN"
      })
    } else {
      wx.showToast({
        title: '语音文件超限',
        icon: 'error'
      })
    }
  },
  streamRecordEnd() {
    manager.stop()
  },
  // 删除录音
  deleteRecord(e) {
    let {
      recordList,
      options
    } = this.data
    let index = e.currentTarget.dataset.index
    recordList.splice(index, 1)
    // options.recordStatus.splice(index, 1)
    // options.recordStatus.push(0)

    // 暂停播放
    setTimeout(() => {
      options.recordStatus = [0, 0, 0]
      innerAudioContext.stop()
    }, 100)

    this.setData({
      recordList,
      options
    })
  },
  /**
   * 初始化语音识别回调
   * 绑定语音播放开始事件
   */
   initRecord: function () {
    let {
      recordList,
      audioUuid,
      options
    } = this.data
    let that = this
    //有新的识别内容返回，则会调用此事件
    manager.onRecognize = (res) => {
      console.log("识别内容变化", res)
    }
    manager.onStart = function (res) {
      console.log("成功开始录音识别", res)
      wx.showLoading({
        title: '开始录音',
      })
    }
    // 识别结束事件
    manager.onStop = ({
      tempFilePath,
      duration,
      fileSize,
      result
    }) => {
      console.log(tempFilePath, duration, fileSize, result)
      recordList.push({
        url: tempFilePath,
        size: fileSize,
        duration: (duration / 1000).toFixed(2)
      })
      this.setData({
        recordList
      })
      // 录制一条语音就发送一条语音
      let index = recordList.length - 1
      that.uploadFile(recordList, index, audioUuid, 2)
      // toast通知
      wx.hideLoading().then(function () {
        wx.showToast({
          title: '结束录音',
        })
      })
      options.recordStatus = [0, 0, 0]
      console.log('识别结束：', {
        tempFilePath,
        duration,
        fileSize,
        result
      })
    }

    // 识别错误事件
    manager.onError = (res) => {
      console.log('识别错误' + res)
    }
    // 音频播放开始回调
    innerAudioContext.onPlay(() => {
      // wx.showToast({
      //   title: '开始播放',
      //   duration: 500
      // })
    })
    // 音频播放结束回调
    innerAudioContext.onEnded(() => {
      // innerAudioContext.stop()
      options.recordStatus = [0, 0, 0]
      this.setData({
        options
      })
    })
  },
  //音频播放
  playAudio(e) {
    let options = this.data.options
    let {
      path: src,
      index
    } = e.currentTarget.dataset

    if (innerAudioContext.src === src && options.recordStatus[index] === 1) {
      // 暂停
      innerAudioContext.pause()
      options.recordStatus = [0, 0, 0]
      options.recordStatus[index] = -1
    } else {
      // 播放
      innerAudioContext.src = src
      innerAudioContext.play()
      options.recordStatus = [0, 0, 0]
      options.recordStatus[index] = 1
    }

    this.setData({
      options
    })
  },
    // 获取字典类型
    getDictInfo() {
      let that = this
      wx.request({
        url: `${baseUrl}/api/dictinfo/list`,
        method: 'GET',
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          let data = res.data.list.filter(item => item.dictType === 'sjddl')
          // console.log(res.data.list)

          data.forEach((c, i, a) => {
            eventTypes[c.dictDesc] = c.child.map(item => item.dictDesc)
          })

          console.log(eventTypes)

          let typeItems = [{
              values: Object.keys(eventTypes),
              className: 'sjddl',
              defaultIndex: 0,
            },
            {
              values: eventTypes['社会治安'],
              className: 'eventCategory',
            }
          ]
          that.setData({
            typeItems
          })
        }
      })
    },
  //音频播放
  playAudio(e) {
    let options = this.data.options
    let {
      path: src,
      index
    } = e.currentTarget.dataset

    if (innerAudioContext.src === src && options.recordStatus[index] === 1) {
      // 暂停
      innerAudioContext.pause()
      options.recordStatus = [0, 0, 0]
      options.recordStatus[index] = -1
    } else {
      // 播放
      innerAudioContext.src = src
      innerAudioContext.play()
      options.recordStatus = [0, 0, 0]
      options.recordStatus[index] = 1
    }

    this.setData({
      options
    })
  },
  // 获取字典类型
  getDictInfo() {
    let that = this
    wx.request({
      url: `${baseUrl}/api/dictinfo/list`,
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        let data = res.data.list.filter(item => item.dictType === 'sjddl')
        // console.log(res.data.list)

        data.forEach((c, i, a) => {
          eventTypes[c.dictDesc] = c.child.map(item => item.dictDesc)
        })

        console.log(eventTypes)

        let typeItems = [{
            values: Object.keys(eventTypes),
            className: 'sjddl',
            defaultIndex: 0,
          },
          {
            values: eventTypes['社会治安'],
            className: 'eventCategory',
          }
        ]
        that.setData({
          typeItems
        })
      }
    })
  },

   /**
   * 生成uuid
   * 绑定语音播放开始事件
   */
    initUuid() {
      let imageUuid = uuidGen.uuid()
      let videoUuid = uuidGen.uuid()
      let audioUuid = uuidGen.uuid()
      this.setData({
        imageUuid,
        videoUuid,
        audioUuid
      })
    },
  /**
   * 提交表单
   */
   submitForm(e) {
    let that = this
    let {
      formData,
      photosList,
      videosList,
      recordList,
      videoUuid,
      audioUuid,
      imageUuid
    } = this.data
    let {
      self
    } = e.currentTarget.dataset
    console.log(this.data.formData)
    let uuid = []
    if (photosList.length) {
      uuid.push(imageUuid)
    }
    if (videosList.length) {
      uuid.push(videoUuid)
    }
    if (recordList.length) {
      uuid.push(audioUuid)
    }
    wx.showLoading({
      title: '上传中，请稍等',
      icon: 'success',
      mask: true
    })
    wx.request({
      // url: 'http://192.168.0.43:8081/api/eventinfo/save',
      url: `${baseUrl}/api/eventTodo/handle`,
      method: 'POST',
      header: {
        'token': wx.getStorageSync('token')
      },
      data: {
        // eventtitle: formData.eventName,
        // sjddl: formData.eventType[0],
        // eventCategory: formData.eventType[1],
        // eventNature: formData.level,
        // happenTime: formData.time,
        // eventAddress: formData.address,
        // eventContent: formData.text,
        // selfDisposal: +self,
        // uuid,
        // appealUser: formData.appealUser,
        // appealPhoneNum: formData.appealPhoneNum
        handleTime: formData.time,
        handleResult: formData.text,
        uuid,
        todoId: that.data.todoId
      },
      success: function (res) {
        if (res.data.code === 0) {
          wx.showToast({
            title: '已提交处置',
            icon: 'success',
            duration: 5000,
            mask: true,
            success: function() {
              let type = 1
              let todoId = that.data.todoId
              let dealwith = 'dealwith2' // 处置已设置状态
              wx.navigateTo({
                // url: '../dealwithDetail/dealwithDetail?id=' + id
                url: `../dealwithDetail/dealwithDetail?type=${type}&id=${todoId}&dealwith=${dealwith}`,
              })
              // setTimeout(() => {

              // }, 2000)
            }
          })
        } else {
          wx.showToast({
            title: '上传失败',
            icon: 'error',
            duration: 1000
          })
        }
      },
      fail: function (e) {
        wx.showToast({
          title: '网络异常',
          icon: 'error',
          duration: 1000
        })
      },
      complete() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let type = this.data.type
    let todoId = this.data.todoId
    let dealwith = this.data.dealwith
    return {
      title: '数字人慧勤务平台',
      desc: '数字人慧勤务平台',
      path: `/pages/detailother/detailother?type=${type}&todoId=${todoId}&dealwith=${dealwith}` // 路径，传递参数到指定页面。
     }
  }
})
